// store/points.js - 积分状态管理
import { defineStore } from 'pinia';
import userApi from '../api/user.js';
import { setPoints, getPoints } from '../utils/storage.js';

export const usePointsStore = defineStore('points', {
  state: () => ({
    // 当前积分
    currentPoints: getPoints() || 0,
    // 积分记录
    pointsRecords: [],
    // 分页信息
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    },
    // 积分变动类型
    pointsTypes: {
      INCOME: 'income',
      EXPENSE: 'expense'
    },
    // 积分来源/用途映射
    pointsSourceMap: {
      'task_completed': '完成任务',
      'task_rejected': '任务被拒绝',
      'exchange_reward': '兑换奖励',
      'sign_in': '签到',
      'invite_friend': '邀请好友',
      'system_reward': '系统奖励',
      'system_deduct': '系统扣除',
      'video_watch': '观看视频',
      'video_watch_double': '观看激励视频',
      'other': '其他'
    },
    // 加载状态
    loading: false,
    // 错误信息
    error: null,
    // 筛选条件
    filters: {
      type: '', // income, expense, all
      source: ''
    }
  }),

  getters: {
    // 总积分收入
    totalIncome: (state) => {
      return state.pointsRecords
        .filter(record => record.type === state.pointsTypes.INCOME)
        .reduce((sum, record) => sum + record.points, 0);
    },
    // 总积分支出
    totalExpense: (state) => {
      return state.pointsRecords
        .filter(record => record.type === state.pointsTypes.EXPENSE)
        .reduce((sum, record) => sum + record.points, 0);
    },
    // 积分余额
    balance: (state) => state.currentPoints,
    // 筛选后的积分记录
    filteredRecords: (state) => {
      let records = [...state.pointsRecords];
      
      // 按类型筛选
      if (state.filters.type && state.filters.type !== 'all') {
        records = records.filter(record => record.type === state.filters.type);
      }
      
      // 按来源筛选
      if (state.filters.source) {
        records = records.filter(record => record.source === state.filters.source);
      }
      
      return records;
    },
    // 获取积分来源文本
    getPointsSourceText: (state) => (source) => {
      return state.pointsSourceMap[source] || source || '未知';
    },
    // 获取积分记录图标
    getPointsRecordIcon: (state) => (record) => {
      if (record.type === state.pointsTypes.INCOME) {
        return 'u-icon-plus-circle'; // 根据uView Plus的图标库调整
      } else {
        return 'u-icon-minus-circle';
      }
    },
    // 获取积分记录颜色
    getPointsRecordColor: (state) => (record) => {
      if (record.type === state.pointsTypes.INCOME) {
        return '#67c23a'; // 收入绿色
      } else {
        return '#f56c6c'; // 支出红色
      }
    }
  },

  actions: {
    // 设置当前积分
    setCurrentPoints(points) {
      this.currentPoints = points;
      setPoints(points);
    },

    // 设置积分记录
    setPointsRecords(records) {
      this.pointsRecords = records;
    },

    // 设置分页信息
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
    },

    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        type: '',
        source: ''
      };
    },

    // 获取积分记录
    async fetchPointsRecords(params = {}, append = false) {
      try {
        this.loading = true;
        this.error = null;
        
        const result = await userApi.getPointsRecords(params);
        
        if (result.code === 1) {
          const records = result.data?.list || [];
          
          if (append) {
            // 追加模式（加载更多）
            this.pointsRecords = [...this.pointsRecords, ...records];
          } else {
            // 替换模式（刷新）
            this.pointsRecords = records;
          }
          
          // 更新分页信息
          this.setPagination({
            currentPage: params.page || 1,
            pageSize: params.limit || 10,
            total: result.data?.total || 0,
            hasMore: this.pointsRecords.length < (result.data?.total || 0)
          });
          
          return true;
        } else {
          this.error = result.msg || '获取积分记录失败';
          return false;
        }
      } catch (error) {
        console.error('获取积分记录失败:', error);
        this.error = '获取积分记录失败，请稍后重试';
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 获取用户积分
    async fetchUserPoints() {
      try {
        const result = await userApi.getUserPoints();
        
        if (result.code === 1 && result.data?.points !== undefined) {
          this.setCurrentPoints(result.data.points);
          return true;
        } else {
          this.error = result.msg || '获取用户积分失败';
          return false;
        }
      } catch (error) {
        console.error('获取用户积分失败:', error);
        this.error = '获取用户积分失败，请稍后重试';
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 积分兑换
    async exchangePoints(rewardId, count = 1) {
      try {
        this.loading = true;
        this.error = null;
        
        // 检查积分是否足够
        const rewardInfo = await this.getRewardInfo(rewardId); // 假设这个方法可以获取奖励信息
        if (rewardInfo && rewardInfo.points * count > this.currentPoints) {
          return { success: false, message: '积分不足' };
        }
        
        const result = await userApi.exchangePoints(rewardId, count);
        
        if (result.code === 1) {
          // 更新积分
          if (result.data?.points !== undefined) {
            this.setCurrentPoints(result.data.points);
          }
          
          // 添加兑换记录到列表开头
          const exchangeRecord = {
            id: Date.now().toString(),
            points: rewardInfo?.points * count || 0,
            type: this.pointsTypes.EXPENSE,
            source: 'exchange_reward',
            description: `兑换奖励: ${rewardInfo?.name || '未知奖励'}`,
            created_at: new Date().toISOString()
          };
          this.pointsRecords.unshift(exchangeRecord);
          
          return { success: true, ...result };
        } else {
          return { success: false, message: result.msg || '积分兑换失败' };
        }
      } catch (error) {
        console.error('积分兑换失败:', error);
        return { success: false, message: '积分兑换失败，请稍后重试' };
      } finally {
        this.loading = false;
      }
    },

    // 增加积分
    addPoints(points, source = 'other', description = '') {
      const newPoints = this.currentPoints + points;
      this.setCurrentPoints(newPoints);
      
      // 添加积分记录
      const pointsRecord = {
        id: Date.now().toString(),
        points,
        type: this.pointsTypes.INCOME,
        source,
        description,
        created_at: new Date().toISOString()
      };
      
      this.pointsRecords.unshift(pointsRecord);
      
      return pointsRecord;
    },

    // 减少积分
    reducePoints(points, source = 'other', description = '') {
      const newPoints = Math.max(0, this.currentPoints - points);
      this.setCurrentPoints(newPoints);
      
      // 添加积分记录
      const pointsRecord = {
        id: Date.now().toString(),
        points,
        type: this.pointsTypes.EXPENSE,
        source,
        description,
        created_at: new Date().toISOString()
      };
      
      this.pointsRecords.unshift(pointsRecord);
      
      return pointsRecord;
    },

    // 加载更多积分记录
    async loadMoreRecords() {
      if (!this.pagination.hasMore || this.loading) return false;
      
      const nextPage = this.pagination.currentPage + 1;
      return await this.fetchPointsRecords({
        ...this.filters,
        page: nextPage,
        limit: this.pagination.pageSize
      }, true);
    },

    // 刷新积分记录
    async refreshRecords() {
      return await this.fetchPointsRecords({
        ...this.filters,
        page: 1,
        limit: this.pagination.pageSize
      });
    },

    // 获取奖励信息（示例方法，实际需要调用API）
    async getRewardInfo(rewardId) {
      // 调用实际的API获取奖励信息
      try {
        const result = await userApi.getRewardInfo(rewardId);
        if (result.code === 1) {
          return result.data;
        }
        // 如果API调用失败，返回默认数据
        return {
          id: rewardId,
          name: '示例奖励',
          points: 100
        };
      } catch (error) {
        console.error('获取奖励信息失败:', error);
        // 发生错误时返回默认数据
        return {
          id: rewardId,
          name: '示例奖励',
          points: 100
        };
      }
    },

    // 重置状态
    resetState() {
      this.currentPoints = 0;
      this.pointsRecords = [];
      this.pagination = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        hasMore: true
      };
      this.loading = false;
      this.error = null;
      this.resetFilters();
    }
  }
});